package com.ecode.annotation.builder.http;

import com.alibaba.fastjson.JSONObject;
import com.ecode.annotation.EcodeDo;
import com.ecode.annotation.core.CodeDataPullBuilder;
import com.squareup.okhttp.*;

import java.io.IOException;

/**
 * @ClassName HttpCodeDataPullBuilder
 * @Author mjlft
 * @Date 2021/10/4 11:49
 * @Version 1.0
 * @Description Http配置数据拉取
 */
public class HttpCodeDataPullBuilder implements CodeDataPullBuilder {

    @Override
    public String dataPull(EcodeDo ecodeDo) {
        String result = null;
        String url = ecodeDo.getConfigUrl();
        if(url == null || "".equals(url)){
            throw new RuntimeException("configUrl必须配置");
        }
        MediaType mediaType =  mediaType = MediaType.parse("application/json; charset=utf-8");

        OkHttpClient client = new OkHttpClient();
        JSONObject json = new JSONObject();
        if(ecodeDo.getSys() != null){
            json.put("sys", ecodeDo.getSys());
            json.put("model", ecodeDo.getModel());
            json.put("version", ecodeDo.getVersion());
        }

        RequestBody body = RequestBody.create(mediaType, json.toJSONString());
        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .build();
        Response response = null;
        try {
            response = client.newCall(request).execute();
            result = response.body().string();
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException("调用配置服务失败");
        }
        return result;
    }
}
